<?php
header('Content-Type: application/json');
require('config.php');
require('functions.php');
require('facebooksdk/src/facebook.php');
requireAuth();

$facebook = new Facebook($fbconfig);
$pid = cleanValue($_POST['targetid']);
$numOfLike = intval($_POST['numoflike']);

$tokenUrl = $_POST['access_token'];
$arrResponse = array('error' => array(), 'success' => array());
try{
	if(!preg_match('#access_token=([A-Z0-9a-z]+)#', $tokenUrl, $accessToken)){
		array_push($arrResponse['error'], 'Access token URL was wrong.');
	}
	else{
		$accessToken = str_replace('access_token=', '', $accessToken[0]);
		$graphUrlPermission = "/me/permissions?access_token=".$accessToken;
		$permissions = $facebook->api(_FB_API_VERSION . $graphUrlPermission);
		
		if (!array_key_exists('publish_stream', $permissions['data'][0])) {
			array_push($arrResponse['error'], 'You are not authorized application for publish_stream permission scope.');
		}
		else{
			saveUserToken($accessToken);

			$batch = fbLikeBatchString($pid, $numOfLike);
			foreach($batch as $arrBatch){
				$batchString = '[' . implode(',', $arrBatch) . ']';
				$response = $facebook->api(_FB_API_VERSION . '/?access_token=' . $accessToken, "POST", array('batch' => $batchString, 'include_headers' => 'false'));

				if(is_array($response) && !empty($response)){
					foreach($response as $res){
						$body = json_decode($res['body'], true);
						if($res['code'] == 200 && isset($res['body'])){
							array_push($arrResponse['success'], $body['success']);
							// save to DB
						}
						else{
							if(isset($body['error']['message'])){
								array_push($arrResponse['error'], $body['error']['message']);
							}
							else{
								array_push($arrResponse['error'], null);
							}
						}
					}
				}
			}
		}
	}
}
catch(Exception $e){
	array_push($arrResponse['error'], $e->getMessage());
}
echo json_encode($arrResponse);